//
//  SEGIntegralExchangeConfirmViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/6/1.
//  Copyright © 2017年 陈区. All rights reserved.
//

#if __has_include(<Commom/CommomHeader.h>)
#import <Commom/CommomHeader.h>
#else
#import "CommomHeader.h"
#endif
 
//#if __has_include(<SVProgressHUD/SVProgressHUD.h>)
//#import <SVProgressHUD/SVProgressHUD.h>
//#else
//#import "SVProgressHUD.h"
//#endif
 
#if __has_include(<CommonMediator/SEGMediatorHeader.h>)
#import <CommonMediator/SEGMediatorHeader.h>
#else
#import "SEGMediatorHeader.h"
#endif

#import "SEGIntegralExchangeConfirmViewController.h"
#import "SEGIntegralExchangeConfirmCell.h"
#import "SEGIntegralExchangeConfirmModel.h"
#import "SEGIntegralExchangeResultViewController.h"
#import "SEGIntegralManager.h"

#import "SEGIntegralExchangeConfirmViewModel.h"

@interface SEGIntegralExchangeConfirmViewController ()<UITableViewDelegate, UITableViewDataSource,SEGAdressListViewControllerDelegate,SEGIntegralExchangeConfirmCellDelegate>
/**
 信息列表视图
 */
@property (nonatomic, strong)UITableView *tableView;

/**
 底部支付视图
 */
@property (nonatomic, strong)UIView *bottomView;

/**
 底部支付标签视图
 */
@property (nonatomic, weak)UILabel *numberLabel;

/**
 商品数量
 */
@property (nonatomic, assign) NSUInteger count;

/**
 是否显示地址
 */
@property (nonatomic, assign) BOOL shoulShowAddress;

/**
 手机号
 */
@property (nonatomic, weak)UITextField *phoneField;

/**
 手机号或账号输入框
 */
@property (nonatomic, weak)UITextField *accountField;

//@property (nonatomic, strong) SEGMyManager* myManager;

@property(nonatomic, strong) SEGIntegralExchangeConfirmViewModel *viewModel;
@end

@implementation SEGIntegralExchangeConfirmViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"兑换确认";
    
    self.view.backgroundColor = kColor_bg;
    
    self.count = 1;
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    
    [self getExchangeConfirmInfo];
}

//返回按钮
- (void)onNavigationLeftButtonClicked:(UIButton*)sender
{
    NSArray *controllers = self.navigationController.viewControllers;
//    for (UIViewController *vc in controllers) {
//        if ([vc isKindOfClass:[SEGWebViewLoadController class]]) {
//            SEGWebViewLoadController *webVC = (SEGWebViewLoadController *)vc;
//            webVC.shouldResetNavgation = YES;
//            [self.navigationController popToViewController:vc animated:YES];
//            return;
//        }
//    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma 网络请求
// 获取默认的收获地址
- (void)getDefaultAddress
{
    [self.viewModel getDefaultAddress:^{
        [self.tableView reloadData];
    }];
}

- (void)getExchangeConfirmInfo
{
    [self.viewModel getExchangeConfirmInfoWithIdString:self.idString completed:^(BOOL isSuccessed, NSString * _Nonnull errorMessage, BOOL shoulShowAddress, NSString * _Nonnull coins, NSInteger type) {
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            return;
        }
        self.shoulShowAddress = shoulShowAddress;
        self.numberLabel.text = coins;
        if (type != SEGIntegralProductType_OnlineVirtual) {//只有 线上虚拟发货 不需要地址信息
            [self getDefaultAddress];
        }
        [self.tableView reloadData];
    }];
}

#pragma mark - 按钮响应方法
//确认支付
- (void)segconfirmButtonPressed
{
    [self.viewModel requestExchangeConfirmWithWithIdString:self.idString count:self.count phone:self.phoneField.text account:self.accountField.text completed:^(BOOL isSuccessed, NSString * _Nonnull errorMessage) {
        if (isSuccessed) {
            //兑换成功
            SEGIntegralExchangeResultViewController *resultVC = [[SEGIntegralExchangeResultViewController alloc] init];
            resultVC.descString = errorMessage;
            [self.navigationController pushViewController:resultVC animated:YES];
        }else {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        }
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.shoulShowAddress) {
        return 2;
    }else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.shoulShowAddress && indexPath.section == 0) {
        SEGShippingAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId1" forIndexPath:indexPath];
        [cell showWithModel:self.viewModel.addressData];
        return cell;
    }else {
        SEGIntegralExchangeConfirmCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId2" forIndexPath:indexPath];
        self.phoneField = cell.phoneField;
        if (self.viewModel.addressData.contactPhone.length > 0) {//默认填默认地址的手机号
            self.phoneField.text = self.viewModel.addressData.contactPhone;
        }
        
        self.accountField = cell.accountField;
        [cell showWithModel:self.viewModel.confirmModel count:self.count];
        cell.delegate = self;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 10)];
    view.backgroundColor = kColor_bg;
    return view;
}

- (CGFloat)tableView:(UITableView*)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 100;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (self.shoulShowAddress) {
        if (indexPath.section == 0) {
             return UITableViewAutomaticDimension;
        } else {
            return 143;
        }
    } else {
        return 143;
    }
    
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (self.shoulShowAddress) {
        if (indexPath.section == 0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(responseAddressWidh:) name:@"AddressNotification" object:nil];
            
            
            
            NSDictionary *params = @{
                                     @"showType":@(AdressListViewControllerType_Order),
                                     @"delegate":self,
                                     @"addressSelected":[self.viewModel.addressData.id length] > 0 ? self.viewModel.addressData.id : kAccountAddressId,
                                     @"shouldShowConfirmView":@"",
                                     @"winnerId":@""};
            
            [self.navigationController pushViewController:[[SEGUhomeMediator sharedInstance] seg_initSEGAdressListViewController:params] animated:YES];
        }
    }
}

- (void)responseAddressWidh:(NSNotification*)sender
{
    self.viewModel.addressData = [sender object];
    [self.tableView reloadData];
}

- (void)responseAddressWidhData:(SEGAddressModel*)data
{
    self.viewModel.addressData = data;
    [self.tableView reloadData];
}

- (void)changeToCount:(NSUInteger)count shouldRequest:(BOOL)shouldRequest
{
    if (shouldRequest) {
        //检测商品数量是否足够
        [self.viewModel requestIntegralExchangeJudgeQuantityWithIdString:self.idString count:count completed:^(BOOL isSuccessed, NSString * _Nonnull errorMessage, NSString * _Nonnull total) {
            if (!isSuccessed) {
                [SEGAlertView showTmepMessageWithMessage:errorMessage];
                return;
                
            }
            self.count = count;
            self.numberLabel.text = total;
            [self.tableView reloadData];
        }];
    }else {
        self.count = count;
        [self.tableView reloadData];
        NSUInteger total = [self.viewModel.confirmModel.coins integerValue] * count;
        self.numberLabel.text = [NSString stringWithFormat:@"应付：%lu积分",(unsigned long)total];
    }
}

#pragma mark - getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kNavigationBarAndStatusBarHeight - 44 - LYSafeAreaBottom()) style:UITableViewStylePlain];
        _tableView.backgroundColor = kColor_bg;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_tableView registerClass:[SEGShippingAddressTableViewCell class] forCellReuseIdentifier:@"cellId1"];
        [_tableView registerClass:[SEGIntegralExchangeConfirmCell class] forCellReuseIdentifier:@"cellId2"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) -kNavigationBarAndStatusBarHeight - 44 - LYSafeAreaBottom(), LYScreenWidth(), 44 + LYSafeAreaBottom())];
        _bottomView.backgroundColor = kColor_W;
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, -0.5, LYScreenWidth()-130, 0.5)];
        line.backgroundColor = kColor_L2;
        [_bottomView addSubview:line];

        UIButton *confirmButton = [[UIButton alloc] init];
        [confirmButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [confirmButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [confirmButton setTitleColor:kColor_W forState:UIControlStateNormal];
        confirmButton.titleLabel.font = kFont_16;
        [confirmButton setTitle:@"确认支付" forState:UIControlStateNormal];
        [confirmButton addTarget:self action:@selector(segconfirmButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:confirmButton];
        [confirmButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self->_bottomView);
            make.width.mas_equalTo(130);
            make.height.mas_equalTo(44);
        }];
        
        UILabel *numberLabel = [[UILabel alloc] init];
        numberLabel.font = kFont_13;
        numberLabel.textColor = kColor_1;
        [_bottomView addSubview:numberLabel];
        [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(confirmButton);
            make.right.equalTo(confirmButton.mas_left).mas_offset(-15);
        }];
        self.numberLabel = numberLabel;
    }
    return _bottomView;
}




#pragma mark - init Views
-(void)segInitViews{

}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
}

#pragma mark - getter
-(SEGIntegralExchangeConfirmViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGIntegralExchangeConfirmViewModel alloc]init];
    }
    return _viewModel;
}
@end
